#By Daoyu 2010-07-19, mostly rewrite 2010-08-24
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.contrib.auth.models import User
from django.db.models import Q

from uncle.users.views import get_all_cat_skill_tool_tag
from uncle.users.models import *
from uncle.util.page import *

#-------------------------------------------------------------------------------
# Manage the categories.
#-------------------------------------------------------------------------------
@login_required
def manage_category(request):
    skts = get_all_cat_skill_tool_tag()
    ca = None
    if request.GET.has_key('ca'):
        ca = Category.objects.get(id = request.GET['ca'])

    return render_to_response('user/categories.html',
          {'skts':skts, 'ca':ca, },
          context_instance = RequestContext(request))

#-------------------------------------------------------------------------------
# Delete the specified category/skill/tool/tag.
#-------------------------------------------------------------------------------
@login_required
def delete_cat(request):
    if request.GET.has_key('tool'):
        Tool.objects.filter(id = request.GET['tool']).delete()
    elif request.GET.has_key('skill'):
        Skill.objects.filter(id = request.GET['skill']).delete()
    elif request.GET.has_key('tag'):
        Tag.objects.filter(id = request.GET['tag']).delete()
    elif request.GET.has_key('category'):
        Category.objects.filter(id = request.GET['category']).delete()

    request.user.message_set.create(message = 'Successfully deleted!')

    if request.GET.has_key('c_id'):
        return HttpResponseRedirect('/user/category/?ca=' + request.GET['c_id'])
    else:
        return HttpResponseRedirect('/user/category/')

#-------------------------------------------------------------------------------
# New a categoryes, skills, tools and tags.
#-------------------------------------------------------------------------------
@login_required
def new_cat(request):
    objs , temp = {'skill':Skill, 'tool':Tool, 'tag':Tag}, None
    if request.GET['type'] == 'category':
        temp = Category()
    else:
        temp = objs.get(request.GET['type'])()
        _cat = Category.objects.get(id = request.GET['c_id'])
        temp.category = _cat

    temp.name = request.POST['new_name']
    temp.save()

    request.user.message_set.create(message = 'Successfully add a new ' + request.GET['type'] + '!')
    if request.GET.has_key('c_id'):
        return HttpResponseRedirect('/user/category/?ca=' + str(request.GET['c_id']))
    else:
        return HttpResponseRedirect('/user/category/?ca=' + str(temp.id))
